<template>
  <drawer class="c-bg-sgray" :class="drawerVisibility ? ['c-text-hidden']: ''" :drawer-style="{'background-color':'#fff', width: '38%'}" :show.sync="drawerVisibility">

    <div slot="drawer" class="c-h c-contexty-scroll">
      <div class="c-fs32 c-pl32 c-fc-sblack c-pv24" :class="cId===0?'theme-fc':''" @click="clickSideItem(0)">商品类目</div>
      <div v-for="(item,index) in sideList" :key="index">
        <div class="c-fs28 c-fc-sblack c-wb-ba c-pl20 c-pr12 c-pv20" :class="cId==item.gId?'theme-fc':''" @click="clickSideItem(item.gId)">{{item.name}}</div>
        <ul>
          <li class="c-fs24 c-fc-gray c-pl52 c-pv20" v-for="(citem,cindex) in item.childs" :class="cId==citem.gId?'theme-fc':''" @click="clickSideItem(citem.gId)" :key="index+'-'+cindex">
            {{citem.name}}</li>
        </ul>
      </div>
    </div>

    <div>
      <div class="c-minh">
        <div class="fixTop" :class="isApp || $isWxApp() || $unenableTopNav() ? 'c-p-t0':'c-p-t68'">
          <div class="c-ph24 c-pv20 c-bg-white">
            <div class="c-flex-row c-w100 c-aligni-center c-pv10 c-ph20 c-hh52 c-br28 c-p c-bg-sgray" @click="clickSearchBar">
              <span class="iconfont c-fs24 c-fc-gray">&#xe6d6;</span>
              <span class="c-ml10 c-fc-gray c-fs24">请输入搜索内容</span>
            </div>
          </div>
          <div v-if="showDetail" class="c-bg-white c-flex-row c-justify-sb c-bd-b1 c-pb10">
            <div @click="clickSort('recommend')" class="c-flex-column c-justify-center c-hh50 c-fs24 c-fc-xblack c-ph24" :class="sortBy == 'recommend' ? 'theme-fc':''">综合推荐</div>
            <div @click="clickSort('sales')" class="c-flex-column c-justify-center c-hh50 c-fs24 c-fc-xblack c-ph24" :class="sortBy == 'sales' ? 'theme-fc':''">销量</div>
            <div @click="clickSort('price')" class="c-flex-column c-justify-center c-hh50 c-fs24 c-fc-xblack c-ph24">
              <div class="c-flex-row c-aligni-center c-fs24">
                <span :class="sortBy == 'price' ? 'theme-fc':''">价格</span>
                <div class="c-flex-column c-flex-center c-pl6">
                  <span class="iconfont c-fs12" :class="sortBy == 'price' && asc=='asc' ? 'theme-fc' : 'c-fc-D5D7DA'">&#xe604;</span>
                  <span class="iconfont c-fs12" :class="sortBy == 'price' && asc=='desc' ? 'theme-fc' : 'c-fc-D5D7DA'">&#xe601;</span>
                </div>
              </div>
            </div>
            <div @click="clickSort('new')" class="c-flex-column c-justify-center c-hh50 c-fs24 c-fc-xblack c-ph24" :class="sortBy == 'new' ? 'theme-fc':''">最新</div>
            <div class="c-flex-row c-aligni-center c-fs24 c-fc-xblack c-ph40 leftLine" @click='popMore'>
              <span class="iconfont icon-fenlei c-fs36"></span>类目
            </div>
          </div>
        </div>
        <div v-if="!showDetail" class="c-bg-white c-pb20 c-ph10 c-pt100">
          <water-fall v-model="firstLevelMenu" ref="firstLevelMenu">
            <template v-slot:list="{list}">
              <div class="c-ww304 c-br6 c-text-hidden c-mb20 fc-item" v-for="(item,index) in list" :key="index" @click="clickSideItem(item.gcId)">
                <div class="c-w100 c-text-hidden">
                  <img class="c-w100 imgCloseBig" v-lazy="item.avatar || require('@/assets/defult270.png')" alt="" />
                </div>
                <div class="c-fs24 c-fc-gray c-pt24 c-pb30 c-textAlign-c c-w100 c-text-ellipsis1 fc-name">{{item.name}}</div>
              </div>
            </template>
          </water-fall>
          <loading-status-tem class="c-bg-white c-w100 c-center" :noData="firstLevelMenu.length==0" noDataText="暂无分类"></loading-status-tem>
        </div>
        <div v-if="showDetail" class="c-pt164">
          <div class="c-text-hidden c-bg-sgray c-ph12">
            <water-fall v-model="shopList" ref="shopList">
              <template v-slot:list="{list}">
                <div class="c-p c-br6 c-bg-white c-m5 c-text-hidden w100-6" v-for="(item,index) in list" :key="index" @click="clickGoodsItem(item.mgId)">
                  <div class="c-w100 c-text-hidden c-maxh310">
                    <img class="c-w100 imgCloseBig" v-lazy="item.avatar || require('../../../assets/defult270.png')" alt="" />
                  </div>
                  <div class="c-pv20 c-ph20">
                    <div class="c-fs24 c-fc-xblack c-text-ellipsis2"><span v-if="item.flashSales && item.flashSales.sales.status == 2" class="c-fs16 theme-bg c-fc-white c-mr4 c-textAlign-c c-br4 c-pv4 c-ph4">限时{{Number(item.flashSales.price) == 0 ? '免费' : '折扣'}}</span>{{item.name}}</div>
                    <div class="c-aligni-center c-flex-row c-flexw-wrap" v-if="item.cashBack && item.cashBack.detail">
                      <span class="c-mr12 c-fs18 c-pv2 c-ph12 theme-bd1 c-br2 theme-fc c-mt12" v-if="item.cashBack.isDiscount == 1">{{item.cashBack.detail.title + item.cashBack.detail.amount}}</span>
                      <span class="c-fs18 c-pv2 c-ph12 theme-bd1 c-br2 theme-fc c-mt12" v-if="item.cashBack.isFreeShipping == 1">
                        {{item.cashBack.detail.title}}包邮
                      </span>
                    </div>
                    <div class="c-flex-row c-mt12 c-aligni-baseline c-justify-sb">
                      <price-com :price="getPrice(item)" :optimal="item.optimal" :prodType="ckFrom.shopping" :priceTagClass="'c-fs20 c-fc-xmlred'" :numberClass="'c-fc-xmlred'"></price-com>
                      <div class="c-fs22 c-fc-gray">{{item.sales | formatTenThousand}}人已买</div>
                    </div>
                  </div>
                </div>
              </template>
            </water-fall>
          </div>
          <loading-status-tem :dataStatus="dataStatus" noDataText="暂无商品" class="c-bg-sgray"></loading-status-tem>
        </div>

      </div>
    </div>
  </drawer>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import Drawer from "@/components/templates/common/drawer.vue";
import PriceCom from '@/components/templates/common/priceCom.vue'
import waterFall from "@/components/templates/common/waterfall.vue"
import { utilJs } from "@/utils/common.js";
import { goDetails } from "@/utils/goDetails.js"
let pageIndex = 1;
export default {
  name: "ClassificationAll",
  components: {
    loadingStatusTem,
    Drawer,
    waterFall,
    PriceCom
  },
  props: [],
  data() {
    return {
      isApp: false,
      showDetail: false,
      drawerVisibility: false,
      sortBy: "recommend",
      cId: "",
      changeCId: '',
      hasChangeCid: false,
      isToDetail: false,
      asc: "asc",
      firstLevelMenu: [],
      sideList: [],
      currentStatus: "",
      shopList: [],
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      dataStatus: 'HAS_MORE_DATA',
      showBackTop: false,
      ckFrom: global.ckFrom,
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {
    getPrice() {
      return function(item) {
       return item.flashSales && item.flashSales.sales.status == 2 ? item.flashSales.price : item.price
      }
    }
  },
  watch: {
    $route(to, from) {
      // 监听详情页内返回数据不重新加载
      if (to.path == '/mall/shopDetail/shopDetail') {
        this.isToDetail = true;
      } else {
        this.isToDetail = false;
      }
    }
  },
  //如果不是从商品详情页返回（比如从首页进到这个页面），则需要重新请求数据
  beforeRouteLeave(to, from, next) {
    if (to.path != '/mall/shopDetail/shopDetail') {
      this.shopList = [];
    }
    next();
  },
  activated() {
    this.isApp = utilJs.isIOSAppALL() || utilJs.isAndroidApp();
    this.wechatShare();
    this.drawerVisibility = false;
    if (this.$route.query.cId == -1) {
      this.showDetail = false;
      setDocumentTitle("全部分类");
      this.cId = "";
    } else {
      this.showDetail = true;
      setDocumentTitle("商品列表");
      this.cId = Number(this.$route.query.cId);
    }
    this.hasChangeCid = false;
    this.currentStatus = "";
    this.firstLevelMenu = [];
    let list = this.showDetail ? this.shopList : this.firstLevelMenu;
    if (utilJs.checkNeedInitData(list)) {
      this.initData()
    }
    window.addEventListener("scroll", this.onScroll);
  },
  deactivated() {
    this.hasChangeCid = false;
    this.changeCId = '';
    window.removeEventListener("scroll", this.onScroll);
  },
  mounted() { },
  methods: {
    initData() {
      this.dataStatus = 'HAS_MORE_DATA';
      this.shopList = [];
      this.sortBy = "recommend";
      this.asc = "asc";
      this.cId = Number(this.$route.query.cId);
      this.sideList = [];
      pageIndex = 1;
      this.$nextTick(() => {
        if (this.$refs.shopList) {
          this.$refs.shopList.clear();
        }
        if (this.$refs.firstLevelMenu) {
          this.$refs.firstLevelMenu.clear();
        }
      })
      this.getMenu();
      this.getGoods();
    },
    onScroll() {
      let that = this;
      utilJs.handleLoading(function () {
        if (that.dataStatus == 'HAS_MORE_DATA' && that.shopList.length > 0) {
          that.getGoods();
        }
      });
    },
    popMore() {
      this.drawerVisibility = true;
    },
    clickSearchBar() {
      //点击搜索框
      this.$routerGo(this, "push", { path: "/mall/search/searchShop" });
    },
    getMenu() {
      let $this = this;
      utilJs.getMethod(global.apiurl + "goods", function (res) {
        $this.turnMenu(res.categories);
      });
    },
    turnMenu(menuInfo) {
      for (let i = 0; i < menuInfo.length; i++) {
        if (menuInfo[i].parentId == 0) {
          this.firstLevelMenu.push(menuInfo[i]);
        }
      }
      for (let j = 0; j < this.firstLevelMenu.length; j++) {
        let oShopListItem = {
          gId: "",
          name: "",
          childs: []
        };
        oShopListItem.name = this.firstLevelMenu[j].name;
        oShopListItem.gId = this.firstLevelMenu[j].gcId;

        for (let k = 0; k < menuInfo.length; k++) {
          if (menuInfo[k].parentId == this.firstLevelMenu[j].gcId) {
            oShopListItem.childs.push({
              name: menuInfo[k].name,
              gId: menuInfo[k].gcId
            });
          }
        }

        this.sideList.push(oShopListItem);
      }
    },
    clickSideItem(gId) {
      this.hasChangeCid = true;
      this.drawerVisibility = false;
      this.showDetail = true;
      setDocumentTitle("商品列表");
      this.cId = gId;
      this.changeCId = this.cId;
      this.sortBy = "recommend";
      this.asc = "asc";
      pageIndex = 1;
      this.shopList = [];
      if (this.$refs.shopList) {
        this.$refs.shopList.clear();
      }
      if (this.$refs.firstLevelMenu) {
        this.$refs.firstLevelMenu.clear();
      }
      let newUrl = `${window.location.href.split("#")[0]}#/mall/classification/classificationAll?cId=${gId}`;
      history.replaceState('mall', "", newUrl);
      this.getGoods();
      this.wechatShare();
      utilJs.appShare(this);
    },
    getGoods() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      let $this = this;
      $this.dataStatus = 'LOADING';
      let sortStr = "";
      if (this.sortBy == "new") {
        sortStr = "&o=createdAt";
      } else if (this.sortBy == "sales") {
        sortStr = "&o=sales";
      } else if (this.sortBy == "recommend") {
        sortStr = "";
      } else if (this.sortBy == "price") {
        if (this.asc == "asc") {
          sortStr = "&o=price&s=asc";
        } else if (this.asc == "desc") {
          sortStr = "&o=price&s=desc";
        }
      }

      utilJs.getMethod(
        global.apiurl +
        "goods?cId=" +
        this.cId +
        "&page=" +
        pageIndex +
        sortStr,
        function (res) {
          if (pageIndex == 1) {
            $this.shopList = res.goods.data;
          } else {
            $this.shopList = [...$this.shopList, ...res.goods.data];
          }
          if (res.goods.total * 1 == res.goods.to * 1) {
            $this.dataStatus = res.goods.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            $this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
        }, failRes => {
          this.dataStatus = 'DATA_ERROR';
        });
    },
    clickSort(sortBy) {
      if (this.sortBy == sortBy) {
        if (sortBy == "price") {
          this.asc = this.asc == "asc" ? "desc" : "asc"
        } else {
          return false;
        }
      } else {
        this.asc = "asc";
        this.sortBy = sortBy;
      }

      pageIndex = 1;
      this.shopList = [];
      if (this.$refs.shopList) {
        this.$refs.shopList.clear();
      }
      if (this.$refs.firstLevelMenu) {
        this.$refs.firstLevelMenu.clear();
      }
      this.getGoods();
    },
    clickGoodsItem(gId) {
      goDetails(this, global.ckFrom.shopping, gId)
    },
    //分享
    wechatShare: function () {
      let title = this.$route.query.cId == -1 ? '全部分类' : '商品列表';
      let shareDesc = "点击查看详情";
      let shareUrl = ''
      if (this.hasChangeCid == false) {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?cId=${this.$route.query.cId}&refereeId=${localStorage.getItem("userId")}`;
      } else {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?cId=${this.changeCId}&refereeId=${localStorage.getItem("userId")}`;
      }
      utilJs.wechatConfig(shareUrl, title, '', shareDesc, function () { });
    },
    //手机端分享
    appShare: function () {
      let title = this.$route.query.cId == -1 ? '全部分类' : '商品列表';
      let shareDesc = "点击查看详情";
      let shareUrl = ''
      if (this.hasChangeCid == false) {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?cId=${this.$route.query.cId}&refereeId=${localStorage.getItem("userId")}`;
      } else {
        shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?cId=${this.changeCId}&refereeId=${localStorage.getItem("userId")}`;
      }
      utilJs.wechatConfig(shareUrl, title, '', shareDesc, function () { });
    }
  },

};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.btn-search-bar {
  background-color: #F5F7FA;
  border-radius: 0.7rem;
  color: #999;
}
.item-bd-left5 {
  border-left: 0.0625rem solid #f2f2f2;
}
.item-bd-right5 {
  border-right: 0.0625rem solid #f2f2f2;
}
.fc-item {
  text-align: center;
  box-shadow: 1px 1px 2px 2px #f2f2f2;
}
.fc-name {
  margin-top: 0.1rem;
}
.ml4 {
  margin-left: 4px;
}
.c-fc-D5D7DA {
  color: #D5D7DA;
}
.c-mt-12 {
  margin-top: -0.3rem;
}
.leftLine {
  position: relative;
}
.leftLine::before {
  position: absolute;
  content: "";
  background-color: #e6e6e6;
  width: 0.05rem;
  height: 0.6rem;
  left: 0;
  top: calc(50% - 0.3rem);
}
.transSc6 {
  transform: scale(0.6)
}
.c-mt-4 {
  margin-top: -0.1rem;
}
.fixTop {
  position: fixed;
  z-index: 100;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
  left: 0;
  right: 0;
  max-width: 16rem;
  margin: 0 auto;
  background: #fff;
}
.c-pt156 {
  padding-top: 3.9rem;
}
.c-m5 {
  margin: 5px 0;
}
.c-mh12 {
  margin-left: 0.3rem;
  margin-right: 0.3rem;
}
.c-ww304 {
  width: 7.6rem;
}
.c-ml8 {
  margin-left: 0.2rem;
}
.w100-6 {
    width: calc(100% - 0.2rem);
}
</style>
